<template>
  <view class="container">
    <view class="form-container">
      <view class="form-group">
        <view class="form-label">假期类型</view>
        <view class="form-control"  v-if="quotasData && quotasData.leaveTypes">
          <view class="picker">
            {{  quotasData.leaveTypes.typeName }}
          </view>
          <view class="leave-balance" v-if="quotasData && quotasData.leaveTypes">
            <text class="balance-text">剩余额度: {{ quotasData.daysRemaining }} 天</text>
            <text class="balance-tag" :class="quotasData.leaveTypes.isPaid ? 'paid-tag' : 'unpaid-tag'">
              {{ quotasData.leaveTypes.isPaid ? '带薪' : '无薪' }}
            </text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label">开始日期</view>
        <view class="form-control">
          <picker mode="date" :value="startDate" :start="today" @change="onStartDateChange">
            <view class="picker">
              {{ startDate || '请选择开始日期' }}
            </view>
          </picker>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label">结束日期</view>
        <view class="form-control">
          <picker mode="date" :value="endDate" :start="startDate || today" :end="currentMonthEnd" @change="onEndDateChange">
            <view class="picker">
              {{ endDate || '请选择结束日期' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 只有当开始日期和结束日期相同时才显示时间段选择器 -->
      <view class="form-group" v-if="startDate && endDate && startDate === endDate">
        <view class="form-label">时间段</view>
        <view class="form-control">
          <picker mode="selector" :range="periodLabels" :value="periodIndex" @change="onPeriodChange">
            <view class="picker">
              {{ selectedPeriodText || '请选择时间段' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 只有当时间段选择器显示且不是全天时才显示提示 -->
      <view class="form-group" v-if="startDate && endDate && startDate === endDate && selectedPeriod !== 'whole_day'">
        <view class="form-control">
          <view class="period-tip">
            <text class="tip-icon">💡</text>
            <text class="tip-text">
              {{ selectedPeriod === 'MORNING' ? '上午' : '下午' }}请假，当天按0.5天计算
            </text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label">请假原因</view>
        <view class="form-control">
          <textarea v-model="reason" placeholder="请输入请假原因" class="reason-textarea" maxlength="500"></textarea>
        </view>
      </view>

      <view class="form-group" v-if="totalDays > 0">
        <view class="form-label">申请天数</view>
        <view class="form-control days-display">
          <text class="days-value">{{ totalDays }} 天</text>
          <text class="remaining-days" v-if="quotasData">
            (剩余: {{ (quotasData.daysRemaining - totalDays).toFixed(1) }} 天)
          </text>
        </view>
      </view>
    </view>

    <view class="validation-tips">
      <view class="tip-item" v-if="! quotasData">请等待假期类型加载完成</view>
      <view class="tip-item" v-if="!startDate">请选择开始日期</view>
      <view class="tip-item" v-if="!endDate">请选择结束日期</view>
      <view class="tip-item" v-if="isNegativeDays">
        结束日期不能早于开始日期
      </view>
      <view class="tip-item" v-if="isCrossMonth">
        申请休假不能跨月，请选择当月内的日期
      </view>
      <view class="tip-item" v-if="startDate && endDate && startDate === endDate && !selectedPeriod">
        请选择时间段
      </view>
      <view class="tip-item" v-if="quotasData  && totalDays > quotasData.daysRemaining">
        申请天数超过剩余假期额度
      </view>
    </view>

    <view class="action-buttons">
      <button class="secondary-btn" @click="goBack">取消</button>
      <button class="primary-btn" @click="submitApplication"
              :class="{ 'disabled-btn': !canSubmit }"
              :disabled="!canSubmit">
        提交申请
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      quotasData:null,
      quotasId: null,
      applyLeaveFrom:{},
      startDate: '',
      endDate: '',
      selectedPeriod: 'MORNING', // 默认时间段为上午
      periodIndex: 0, // 默认选中上午
      reason: '',
      today: '',
      periods: [
        { value: 'MORNING', label: '上午' },
        { value: 'AFTERNOON', label: '下午' },
        { value: 'WHOLE_DAY', label: '全天' }
      ],
      currentMonth: '', // 当前月份
      currentMonthEnd: '' // 当前月最后一天
    }
  },
  computed: {
    // 时间段标签数组，用于picker组件
    periodLabels() {
      return this.periods.map(p => p.label)
    },

    // 当前选择的时间段文本
    selectedPeriodText() {
      const period = this.periods.find(p => p.value === this.selectedPeriod)
      return period ? period.label : ''
    },

    // 计算总天数
    totalDays() {
      if (!this.startDate || !this.endDate) return 0

      const start = new Date(this.startDate)
      const end = new Date(this.endDate)

      // 计算天数差
      const timeDiff = end.getTime() - start.getTime()
      const daysDiff = timeDiff / (1000 * 3600 * 24)
      const fullDays = Math.max(0, Math.floor(daysDiff)) // 整天数

      if (fullDays === 0) {
        // 同一天
        return this.selectedPeriod === 'WHOLE_DAY' ? 1 : 0.5
      } else {
        // 不同天，直接按整天计算
        return fullDays + 1
      }
    },

    // 天数是否为负数
    isNegativeDays() {
      if (!this.startDate || !this.endDate) return false

      const start = new Date(this.startDate)
      const end = new Date(this.endDate)
      return end < start
    },

    // 是否跨月
    isCrossMonth() {
      if (!this.startDate || !this.endDate) return false

      const startMonth = new Date(this.startDate).getMonth()
      const endMonth = new Date(this.endDate).getMonth()
      return startMonth !== endMonth
    },

    // 是否可以提交申请
    canSubmit() {
      return (
          this.startDate &&
          this.quotasData &&
          this.endDate &&
          !this.isNegativeDays &&
          !this.isCrossMonth &&
          (!this.showPeriodSelector || this.selectedPeriod) &&
          this.totalDays <= (this.quotasData.daysRemaining || 0)
      )
    },

    // 是否显示时间段选择器
    showPeriodSelector() {
      return this.startDate && this.endDate && this.startDate === this.endDate
    }
  },
  onLoad(options) {
    this.today = this.getToday()
    this.currentMonth = this.getMonthStart()
    this.currentMonthEnd = this.getMonthEnd()

    // 设置默认开始和结束日期为当天
    this.startDate = this.today
    this.endDate = this.today

    if (options.id) {
      this.quotasId = parseInt(options.id)
    } else {
      // 如果没有传入leaveTypeId，显示错误提示
      uni.showModal({
        title: '参数错误',
        content: '未指定假期类型，请从假期列表进入申请页面。',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
      return
    }

    this.loadQuotasById()
  },
  methods: {
    // 加载假期类型
    loadQuotasById() {
      if (this.quotasId) {
        this.req({
          url: '/leave/quotas/'+parseInt(this.quotasId),
          method: 'GET'
        }).then(res => {
          this.quotasData = res.data
        })
      }
    },

    // 获取今天日期
    getToday() {
      const date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 获取当月第一天
    getMonthStart() {
      const date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      return `${year}-${month}-01`
    },

    // 获取当月最后一天
    getMonthEnd() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const lastDay = new Date(year, month, 0).getDate()
      return `${year}-${month.toString().padStart(2, '0')}-${lastDay.toString().padStart(2, '0')}`
    },

    // 开始日期变更
    onStartDateChange(e) {
      this.startDate = e.detail.value

      // 如果结束日期早于开始日期，更新结束日期
      if (this.endDate && new Date(this.endDate) < new Date(this.startDate)) {
        this.endDate = this.startDate
      }

      // 检查是否跨月
      if (this.isCrossMonth) {
        uni.showModal({
          title: '日期选择错误',
          content: '申请休假不能跨月，请选择当月内的日期。',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#1890ff'
        })
      }
    },

    // 结束日期变更
    onEndDateChange(e) {
      this.endDate = e.detail.value

      // 检查并提示申请天数超过剩余额度
      if (this.totalDays > (this.quotasData.daysRemaining || 0)) {
        uni.showModal({
          title: '申请天数超限',
          content: `您申请的天数(${this.totalDays}天)超过了剩余假期额度(${this.quotasData?.remainingDays || 0}天)，请调整日期或假期类型。`,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#1890ff'
        })
      }

      // 检查是否跨月
      if (this.isCrossMonth) {
        uni.showModal({
          title: '日期选择错误',
          content: '申请休假不能跨月，请选择当月内的日期。',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#1890ff'
        })
      }
    },

    // 时间段变更
    onPeriodChange(e) {
      this.periodIndex = e.detail.value
      this.selectedPeriod = this.periods[this.periodIndex].value

      // 显示选择提示
      uni.showToast({
        title: `您选择了${this.selectedPeriodText}请假`,
        icon: 'none',
        duration: 2000
      })
    },

    // 返回
    goBack() {
      uni.navigateBack()
    },

    // 提交申请
    submitApplication() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善申请信息',
          icon: 'none'
        })
        return
      }

      // 提交前确认
      uni.showModal({
        title: '确认提交',
        content: `您确定要申请${this.totalDays}天${this.quotasData.leaveTypes.typeName}吗？`,
        confirmText: '确认提交',
        confirmColor: '#1890ff',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '提交中...'
            })
            this.applyLeaveFrom  = {
              quotasId: this.quotasId,
              startDate: this.startDate,
              endDate: this.endDate,
              period: this.selectedPeriod,
              reason: this.reason,
              workingDays:this.totalDays,
              leaveTypeId: this.quotasData.leaveTypes.id,
            }
            this.req({
              url: '/leave/applications/apply',
              method: 'POST',
              data: this.applyLeaveFrom
            }).then(res => {
              uni.hideLoading()
              uni.showModal({
                title: '申请成功',
                content: `您已成功提交${this.totalDays}天${this.quotasData.leaveTypes.typeName}申请，等待审批`,
                showCancel: false,
                success: () => {
                  uni.navigateBack()
                }
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.form-control {
  position: relative;
}

.picker {
  font-size: 30rpx;
  color: #333;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f2f2f2;
  position: relative;
}

/* 移除选择器的下拉箭头 */
.picker:after {
  display: none;
}

.leave-balance {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
  font-size: 26rpx;
  color: #999;
}

.balance-text {
  margin-right: 16rpx;
}

.balance-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.paid-tag {
  background-color: #e6f7ff;
  color: #1890ff;
}

.unpaid-tag {
  background-color: #fff3f3;
  color: #ff4d4f;
}

.reason-textarea {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.days-display {
  font-size: 32rpx;
  color: #333;
  padding: 16rpx 0;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.days-value {
  color: #1890ff;
  margin-right: 16rpx;
}

.remaining-days {
  font-size: 24rpx;
  color: #999;
}

.period-tip {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #ff7a45;
  padding: 10rpx 0;
  background-color: #fff7e6;
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
}

.tip-icon {
  margin-right: 8rpx;
}

.validation-tips {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.tip-item {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
}

.tip-item::before {
  content: '•';
  margin-right: 8rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #ff7a45;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
}

.secondary-btn, .primary-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  margin: 0 15rpx;
}

.secondary-btn {
  background-color: #fff;
  color: #1890ff;
  border: 1rpx solid #1890ff;
}

.primary-btn {
  background-color: #1890ff;
  color: #fff;
  border: none;
}

.disabled-btn {
  background-color: #a8c7e7;
  color: #e6f7ff;
  cursor: not-allowed;
}
</style>